package com.teamsun.redis;


import org.apache.log4j.Logger;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * Redis操作封装
 */
public class RedisService {

    private static final Logger LOGGER = Logger.getLogger(RedisService.class);

    private JedisPool jedisPool;

    /**
     * 保存对象
     * @param object
     */
    public void setObject(String key, Object object) {
        Jedis jedis = jedisPool.getResource();
        try {
            jedis.set(key.getBytes(), SerializeUtil.serialize(object));
        } catch (Exception e) {
            LOGGER.error("Redis保存对象【" + key + "】失败", e);
        } finally {
            jedisPool.returnResource(jedis);
        }
    }

    /**
     * 获取对象
     * @param key
     * @return
     */
    public Object getObject(String key) {
        Jedis jedis = jedisPool.getResource();
        Object object = null;
        try {
            object = SerializeUtil.unSerialize(jedis.get(key.getBytes()));
        } catch (Exception e) {
            LOGGER.error("Redis获取对象【" + key + "】失败", e);
        } finally {
            jedisPool.returnResource(jedis);
        }
        return object;
    }

    /**
     * 删除Redis数据
     * @param key
     */
    public void removeRedis(String key) {
        Jedis jedis = jedisPool.getResource();
        try {
            jedis.decr(key);
        } catch (Exception e) {
            LOGGER.error("Redis删除对象【" + key + "】失败", e);
        } finally {
            jedisPool.returnResource(jedis);
        }
    }

    /**
     * 保持Redis数据
     * @param key
     * @param value
     */
    public void setRedis(String key, String value) {
        Jedis jedis = jedisPool.getResource();
        try {
            jedis.set(key, value);
        } catch (Exception e) {
            LOGGER.error("Redis保存对象【" + key + "】失败", e);
        } finally {
            jedisPool.returnResource(jedis);
        }
    }

    /**
     * 获取Redis数据
     * @param key
     * @return
     */
    public String getRedis(String key) {
        Jedis jedis = jedisPool.getResource();
        String object = null;
        try {
            object = jedis.get(key);
        } catch (Exception e) {
            LOGGER.error("Redis获取数据【" + key + "】失败", e);
        } finally {
            jedisPool.returnResource(jedis);
        }
        return object;
    }

    public JedisPool getJedisPool() {
        return jedisPool;
    }

    public void setJedisPool(JedisPool jedisPool) {
        this.jedisPool = jedisPool;
    }
}
